from odoo import api, fields, models
from odoo.exceptions import UserError
from odoo.addons.rp_marketing_management.functions.marketing_coupon_func import MarketingCouponFunc
from odoo.addons.rp_marketing_management.functions.marketing_adjustment_func import MarketingAdjustmentFunc
from ...decorate.marketing_function_decorate import record_use_coupon_info

ADJUST_FOR = [('all_mail_route', '所有邮路'), ('single_mail_route', '单一邮路'), ('single_value_add', '单一增值'), ('all_value_add', '所有增值(二级)')]


class RpShipOrderInheritForMarketing(models.Model):
    _inherit = 'rp.ship.order'
    _description = '运输订单'

    # 调价相关
    marketing_adjust_price_flag = fields.Boolean(string='调价状态', default=False, copy=False, required=True)
    marketing_adjust_price_template_ids = fields.Many2many(string='调价模板', comodel_name='rp.marketing.adjust.price.template', column1='rp_ship_order_id', column2='adjust_price_template_id',
                                                           relation='rp_ship_order_adjust_price_template_rel', copy=False, readonly=True)
    mail_route_marketing_adjust_result = fields.Float(string='邮路调后价')
    fulfillment_marketing_adjusted_price = fields.Float(string='头尾程调后价')
    value_added_marketing_adjusted_price = fields.Float(string='增值服务调后价')
    all_adjust_marketing_price = fields.Float(string='总计调价后')

    # 优惠券相关
    rp_shipper_order_coupon_flag = fields.Boolean(string='优惠状态', default=False, copy=False, required=True)
    rp_shipper_order_coupon_line_ids = fields.One2many(string='优惠券明细', comodel_name='rp.shipper.order.coupon.line', inverse_name='rp_shipper_order_id', copy=False, tracking=True)
    discount_sum_for_added = fields.Float(string='增值优惠后', compute='compute_get_discount_price', copy=False, store=True, tracking=True)
    discount_sum_for_mail = fields.Float(string='邮路优惠后', compute='compute_get_discount_price', copy=False, store=True, tracking=True)
    used_coupon_ids_for_mail = fields.Many2many(string='邮路使用的优惠券', comodel_name='rp.customer.coupon', column1='ship_order_mail_id', column2='customer_coupon_id', relation='ship_order_mail_and_customer_coupon_rel', default=False, copy=False)
    discount_sum_for_operation = fields.Float(string='头尾程优惠后', compute='compute_get_discount_price', copy=False, store=True, tracking=True)
    discount_total = fields.Float(string='优惠后总价', copy=False, store=True, tracking=True)

    # 优惠券相关流程字段
    coupon_select_tag = fields.Boolean(string='优惠券选择标志', default=False, tracking=True)

    @api.onchange('step_six')
    def _on_change_for_step_six(self):
        """
        被动调价
        """
        if self.step_six:
            # 获取销售模板中的具体邮路
            selected_sale_template_mail_route_line = MarketingAdjustmentFunc(self.env).backdoor_get_selected_mail_route(self.shipper_mail_route_id, self.send_city_id, self.receive_city_id)
            # 获取调价信息
            adjusted_dict = MarketingAdjustmentFunc(self.env).backdoor_get_adjustment_price_result(self.customer_id, self.shipper_id, selected_sale_template_mail_route_line
                                                                                                   , self.mail_route_sale_adjusted_price, self.rp_ship_order_value_added_line_ids)
            self.update({
                'mail_route_marketing_adjust_result': adjusted_dict.get('sum_for_route'),
                'value_added_marketing_adjusted_price': adjusted_dict.get('sum_for_added'),
                'fulfillment_marketing_adjusted_price': adjusted_dict.get('sum_for_fulfillment'),
                'all_adjust_marketing_price': adjusted_dict.get('all_price_adjust_price'),
                'marketing_adjust_price_flag': adjusted_dict.get('adjusted_state'),
                'marketing_adjust_price_template_ids': adjusted_dict.get('related_template_id')
            })

    def action_get_available_coupon(self):
        """
        获取可用优惠券列表
        """
        if self.state != 'unpaid':
            raise UserError('您的订单步骤尚未完成六步或已经支付完成！')
        available_sva = MarketingCouponFunc(self.env).backdoor_get_available_coupon(customer_id=self.customer_id,
                                                                                    rp_ship_order_value_added_line_ids=self.rp_ship_order_value_added_line_ids,
                                                                                    shipper_mail_route_id=self.shipper_mail_route_id,
                                                                                    all_adjust_marketing_price=self.all_adjust_marketing_price)
        action = self.env.ref('rp_marketing_management.action_rp_available_customer_coupon_tran')
        result = action.read()[0]

        result['name'] = '可用优惠券'
        result['domain'] = f"[('id','in',{available_sva.ids})]"
        result['context'] = {'create': False, 'ship_order_id': self.id, 'show_display': 1}
        result['display_name'] = None
        result['target'] = 'new'
        return result

    @api.depends('rp_shipper_order_coupon_line_ids')
    def compute_get_discount_price(self):
        for record in self:
            # 计算优惠后价格
            if len(record.rp_shipper_order_coupon_line_ids.ids) > 0:
                response_dict = MarketingCouponFunc(record.env).backdoor_get_discounted_total_price(record.rp_shipper_order_coupon_line_ids, record.rp_ship_order_value_added_line_ids, record.mail_route_marketing_adjust_result, record.shipper_mail_route_id)
                record.write({
                    'discount_sum_for_added': response_dict.get('value_add_discount_price', False),
                    'discount_sum_for_mail': response_dict.get('mail_discount_price', False),
                    'discount_sum_for_operation': response_dict.get('sum_for_operation', False),
                    'discount_total': response_dict.get('value_add_discount_price', False) + response_dict.get('mail_discount_price', False) + response_dict.get('sum_for_operation', False),
                    'used_coupon_ids_for_mail': [(6, 0, response_dict.get('used_coupon_ids_for_mail', False))],
                    'rp_shipper_order_coupon_flag': True
                })
            else:
                record.write({
                    'discount_sum_for_added': record.value_added_marketing_adjusted_price,
                    'discount_sum_for_mail': record.mail_route_marketing_adjust_result,
                    'discount_sum_for_operation': record.fulfillment_marketing_adjusted_price,
                    'discount_total': record.value_added_marketing_adjusted_price + record.mail_route_marketing_adjust_result + record.fulfillment_marketing_adjusted_price,
                    'used_coupon_ids_for_mail': False
                })

    @api.depends('marketing_adjust_price_flag', 'rp_shipper_order_coupon_flag')
    def _depends_compute_actual_price(self):
        """ 计算实价 """
        # 执行父类的实价逻辑（防止安装营销后未完成六步的无法计算实价问题）
        super()._depends_compute_actual_price()
        for s in self:
            # 调价成功，未使用优惠券
            if s.marketing_adjust_price_flag and not s.rp_shipper_order_coupon_flag:
                s.write({'mail_route_actual_price': s.mail_route_marketing_adjust_result,
                         'fulfillment_total_actual_price': s.fulfillment_marketing_adjusted_price,
                         'value_added_total_actual_price': s.value_added_marketing_adjusted_price,
                         'total_actual_price': s.all_adjust_marketing_price})
            # 调价成功，且使用优惠券
            if s.marketing_adjust_price_flag and s.rp_shipper_order_coupon_flag:
                s.write({'mail_route_actual_price': s.discount_sum_for_mail,
                         'fulfillment_total_actual_price': s.discount_sum_for_operation,
                         'value_added_total_actual_price': s.discount_sum_for_added,
                         'total_actual_price': s.discount_total})

    @record_use_coupon_info
    def action_for_pay(self):
        """支付后相关逻辑"""
        super(RpShipOrderInheritForMarketing, self).action_for_pay()
        # 处理优惠券
        if self.pay_flag:
            if self.rp_shipper_order_coupon_flag and len(self.rp_shipper_order_coupon_line_ids.ids):
                for item in self.rp_shipper_order_coupon_line_ids:
                    # 优惠券状态变更
                    item.rp_customer_coupon_id.write({'rp_coupon_status': 'used'})
                    # 优惠券模板信息变更【使用次数】
                    usage_number = item.rp_customer_coupon_id.rp_coupon_template_id.usage_number
                    item.rp_customer_coupon_id.rp_coupon_template_id.write({'usage_number': usage_number + 1})

    """
    Button Function
    """

    def select_coupon(self):
        """
        选择优惠券
        """
        # 选择可用的优惠券
        result = self.action_get_available_coupon()
        return result

    def cancel_coupon(self):
        """
        取消使用优惠券
        """
        self.write(
            {
                'coupon_select_tag': False,
                'rp_shipper_order_coupon_line_ids': False,  # 清除对应头尾程，
                'discount_sum_for_added': False,
                'discount_sum_for_mail': False,
                'used_coupon_ids_for_mail': False,
                'discount_sum_for_operation': False,
                'discount_total': False,
                'rp_shipper_order_coupon_flag': False  # 优惠券使用状态，充值优惠价格
            })

    def turn_coupon(self):
        self.ensure_one()
        self.write({'process_step': 'coupon'})
